import sys
import os
# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_root)

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse

# 修复导入路径
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "routes"))
from backend.routes import fault_routes, stats_routes, email_routes, system_log_routes

app = FastAPI(title="Operations Daily Fault Handling Report API")

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含路由
app.include_router(fault_routes.router, prefix="/api/faults", tags=["faults"])
app.include_router(stats_routes.router, prefix="/api/stats", tags=["stats"])
app.include_router(email_routes.router, prefix="/api/email", tags=["email"])
app.include_router(system_log_routes.router, prefix="/api/logs", tags=["logs"])


# 挂载静态文件目录（放在路由之后）
frontend_dir = os.path.join(project_root, "frontend")
if os.path.exists(frontend_dir):
    # 前端目录被挂载为静态文件服务：/static
    #所以您可以通过访问 http://localhost:8000/static/ 或 http://localhost:8000/static/index.html 来查看前端页面。
    app.mount("/static", StaticFiles(directory=frontend_dir, html=True), name="frontend")
else:
    print(f"警告: 前端目录 {frontend_dir} 不存在")

@app.get("/")
async def root():
    return {"message": "Operations Daily Fault Handling Report API"}

# 设置默认响应编码
@app.middleware("http")
async def add_default_encoding_header(request, call_next):
    response = await call_next(request)
    if response.headers.get("content-type", "").startswith("application/json"):
        response.headers["content-type"] = "application/json; charset=utf-8"
    return response

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)